package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.commmon.R;
import org.example.dto.MedicineDto;
import org.example.pojo.Category;
import org.example.pojo.Medicine;
import org.example.pojo.MedicineStandard;
import org.example.service.CategoryService;
import org.example.service.MedicineService;
import org.example.service.MedicineStandardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class MedicineController {

    @Autowired
    private MedicineStandardService medicineStandardService;
    @Autowired
    private MedicineService medicineService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 向药品和使用标准表添加数据
     *
     * @param medicineDto
     * @return
     */

    /**
     MedicineDto(
     flavors=[MedicineStandard(id=null, medicineId=null, name=服用时段, value=["早餐","午餐","晚餐"],createTime=null, updateTime=null, createUser=null, updateUser=null, isDeleted=null)],
     categoryName=null, copies=null)
     *
      */

    @PostMapping
    public R<String> save(@RequestBody MedicineDto medicineDto) {
        System.out.println(medicineDto);
        medicineService.saveWithStandard(medicineDto);

        //清理某个分类的药品的缓存
        Set keys = redisTemplate.keys("medicine_"+medicineDto.getCategoryId()+"_1");
        redisTemplate.delete(keys);
        return R.success("新增药品成功");


    }

    /**
     * 药品信息的分页
     * http://localhost:8080/medicine/page?page=1&pageSize=10
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {


        //数据返回给前端

        return  medicineService.getPage(page,pageSize,name);
    }


    /**
     * 修改药品的信息
     * 前端点击修改按钮
     * 跳到修改页面 同时加载分类的信息（CategoryController已经完成）
     * 根据药品的id回显药品的信息
     * 图片展示
     * 保存将数据提交
     */


    //回显
    //http://localhost:8080/medicine/1683465010537758721
    @GetMapping("/{id}")
    public R<MedicineDto> get(@PathVariable Long id){
            return  R.success(medicineService.getByIdWithStandard(id));

    }

    //修改
//    URL: http://localhost:8080/medicine

    @PutMapping
    public R<String> update(@RequestBody MedicineDto medicineDto) {
        medicineService.updateWithStandard(medicineDto);

        //清理某个分类的药品的缓存
        Set keys = redisTemplate.keys("medicine_"+medicineDto.getCategoryId()+"_1");
        redisTemplate.delete(keys);
        return R.success("新增药品成功");


    }





    //批量删除
//    http://localhost:8080/medicine?ids=1683465010537758721,1683450179610542082

    /**
     * 删除药品信息和对应的使用标准信息
     * @param ids
     */


    @DeleteMapping
    public R<String> deleteByIds(@RequestParam  List<Long> ids){
      medicineService.deleteByIds(ids);
      return R.success("批量删除成功");
    }



    //启售停售
//    http://localhost:8080/medicine/status/0?ids=1683448537333264386
    @PostMapping("/status/{status}")
    public R<String> close(@RequestParam  List<Long> ids,@PathVariable Integer status){
        for (int i = 0; i < ids.size(); i++) {
            Medicine medicine = medicineService.getById(ids.get(i));
            medicine.setStatus(status);
            medicineService.updateById(medicine);
        }

        return R.success("修改成功");

    }



//    回显
//    http://localhost:8080/medicine/list?categoryId=1413384954989060097

//    @GetMapping("/list")
//    public R<List<Medicine>> list(Long categoryId){
//        LambdaQueryWrapper<Medicine> medicineLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        medicineLambdaQueryWrapper.eq(Medicine::getCategoryId,categoryId);
//        medicineLambdaQueryWrapper.eq(Medicine::getStatus,1);
//        //排序
//        medicineLambdaQueryWrapper.orderByDesc(Medicine::getSort).orderByDesc(Medicine::getUpdateTime);
//        List<Medicine> list = medicineService.list(medicineLambdaQueryWrapper);
//        return R.success(list);
//    }





    @GetMapping("/list")
    public R<List<MedicineDto>> list(Medicine medicine){

        //设计缓存
        List<MedicineDto> medicineDtoList=null;
        //medicine_123_1 根据分类id从缓存查询药品
        String key="medicine_"+medicine.getCategoryId()+"_"+medicine.getStatus();
        medicineDtoList= (List<MedicineDto>) redisTemplate.opsForValue().get(key);

        //1.如果缓存存在 直接返回
        if (medicineDtoList!=null) return  R.success(medicineDtoList);




        //2.若不存在 则无需查询数据库
        LambdaQueryWrapper<Medicine> medicineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        medicineLambdaQueryWrapper.eq(Medicine::getCategoryId,medicine.getCategoryId());
        medicineLambdaQueryWrapper.eq(Medicine::getStatus,1);
        //排序
        medicineLambdaQueryWrapper.orderByDesc(Medicine::getSort).orderByDesc(Medicine::getUpdateTime);
        List<Medicine> list = medicineService.list(medicineLambdaQueryWrapper);
        medicineDtoList=list.stream().map((item) -> {
            //将普通属性拷贝给Dto对象
            MedicineDto medicineDto = new MedicineDto();
            BeanUtils.copyProperties(item,medicineDto);

            Long categoryId = item.getCategoryId();
            //通过id拿到分类对象
            Category categoryById = categoryService.getById(categoryId);
            //通过分类对象拿到分类的名称
            String categoryName = categoryById.getName();
            //最后将分类名传给Dto对象
            medicineDto.setCategoryName(categoryName);

            //使用标准也设置到medicineDto中
            Long medicineId = item.getId();           //拿到药品的id
            //通过药品的id拿到对应的使用标准列表
            LambdaQueryWrapper<MedicineStandard> medicineStandardLambdaQueryWrapper = new LambdaQueryWrapper<>();
            medicineStandardLambdaQueryWrapper.eq(MedicineStandard::getMedicineId,medicineId);
            List<MedicineStandard> medicineStandardList = medicineStandardService.list(medicineStandardLambdaQueryWrapper);
            //将medicineStandardList装到medicineDto对象
            medicineDto.setStandards(medicineStandardList);


            return medicineDto;
        }).collect(Collectors.toList());
        //查询完成后 将数据放到缓存，当下次查询时 就可以用缓存中的数据
        redisTemplate.opsForValue().set(key,medicineDtoList,60, TimeUnit.MINUTES);


        return R.success(medicineDtoList);

    }






}
